from typing import List

class Solution:
    def minSwapsCouples(self, row: List[int]) -> int:
        n = len(row)

        parents = list(range(n + 1))
        sizes = [1] * (n + 1)

        def find(x):
            while parents[x] != x:
                parents[x] = find(parents[x])
                x = parents[x]
            return x

        def union(x, y):
            x = find(x)
            y = find(y)
            if x == y:
                return True
            if sizes[x] < sizes[y]:
                x, y = y, x
            parents[y] = x
            sizes[x] += sizes[y]
            return False

        for i in range(0, n, 2):
            union(i, i+1)
            union(row[i], row[i+1])

        result = 0
        for i in range(n):
            if parents[i] == i:
                result += sizes[i] // 2 - 1

        return result
